
  <div class="layui-card">
    <div class="layui-card-body">
      <div class="layui-form-item" style="margin-bottom: 15px;">
        <div class="layui-inline">
          <input type="text" id="searchAuthGroup" placeholder="搜索分类名称..." class="layui-input" style="width: 250px;">
        </div>
        <div class="layui-inline">
          <button class="layui-btn" id="searchAuthGroupBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
          <button class="layui-btn layui-btn-primary" id="refreshAuthGroupBtn"><i class="layui-icon layui-icon-refresh"></i> 刷新</button>
        </div>
        <div class="layui-inline" style="float: right;">
          <button class="layui-btn" id="addAuthGroupBtn"><i class="layui-icon layui-icon-addition"></i> 添加分类</button>
        </div>
      </div>

      <table class="layui-table" lay-skin="line">
        <colgroup>
          <col width="80">
          <col width="200">
          <col>
          <col width="180">
          <col width="180">
          <col width="200">
        </colgroup>
        <thead>
          <tr>
            <th>排序</th>
            <th>分类名称</th>
            <th>描述</th>
            <th>创建时间</th>
            <th>最后修改时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="authGroupTable">
        </tbody>
      </table>
    </div>
  </div>

<!-- 权限分类表单 -->
<script type="text/html" id="authGroupFormTpl">
  <form class="layui-form" style="padding: 20px;" lay-filter="authGroupForm">
    <input type="hidden" name="id">
    <div class="layui-form-item">
      <label class="layui-form-label">分类名称</label>
      <div class="layui-input-block">
        <input type="text" name="name" required lay-verify="required" placeholder="请输入分类名称" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">描述</label>
      <div class="layui-input-block">
        <textarea name="desc" placeholder="请输入分类描述" class="layui-textarea"></textarea>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">排序值</label>
      <div class="layui-input-block">
        <input type="number" name="sort" value="0" placeholder="请输入排序值（数值越小排在前面）" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit lay-filter="submitAuthGroup">保存</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
</script>

<script>
// 从后端获取的数据
var authGroupData = [];  // 权限大分类数据
var authData = [];       // 权限组数据

layui.use(['layer', 'form'], function(){
  var layer = layui.layer;
  var form = layui.form;
  
  // 格式化时间
  function formatTime(timestamp) {
    if (!timestamp) return '-';
    // 如果是时间戳，转换为格式化时间
    var date = new Date(timestamp);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' + 
           String(date.getMinutes()).padStart(2, '0') + ':' + 
           String(date.getSeconds()).padStart(2, '0');
  }
  
  // 从后端获取数据
  function fetchData() {
    // 显示加载提示
    var loading = layer.load(2);
    
    // 获取权限大分类数据
    fetch('/auth/group')
      .then(response => response.json())
      .then(groupResult => {
        if (groupResult.result) {
          authGroupData = groupResult.data || [];
        }
        
        // 获取权限组数据
        return fetch('/auth/auth');
      })
      .then(response => response.json())
      .then(authResult => {
        layer.close(loading); // 关闭加载提示
        if (authResult.result) {
          authData = authResult.data || [];
        }
        renderAuthGroup();
      })
      .catch(error => {
        layer.close(loading); // 关闭加载提示
        layer.msg('数据加载失败: ' + error.message, {icon: 2});
        console.error('Error:', error);
        // 即使出错也渲染界面，使用现有数据
        renderAuthGroup();
      });
  }
  
  // 渲染权限分类
  function renderAuthGroup() {
    var tbody = document.getElementById('authGroupTable');
    tbody.innerHTML = '';
    
    var searchValue = document.getElementById('searchAuthGroup').value.toLowerCase();
    var filtered = authGroupData.filter(function(group) {
      return group.name.toLowerCase().includes(searchValue) ||
             (group.desc && group.desc.toLowerCase().includes(searchValue));
    });
    
    filtered.forEach(function(group) {
      var relatedAuthCount = authData.filter(function(auth) {
        return auth.groupID === group.id;
      }).length;
      
      var tr = document.createElement('tr');
      tr.innerHTML = `
        <td><strong>${group.sort || 0}</strong></td>
        <td><strong>${group.name}</strong><div class="layui-font-gray layui-font-12">关联权限组: ${relatedAuthCount}个</div></td>
        <td>${group.desc || '-'}</td>
        <td>${group.createTime}</td>
        <td>${group.updateTime}</td>
        <td>
          <button class="layui-btn layui-btn-xs layui-btn-normal edit-authGroup" data-id="${group.id}">编辑</button>
          <button class="layui-btn layui-btn-xs layui-btn-danger delete-authGroup" data-id="${group.id}">删除</button>
        </td>
      `;
      tbody.appendChild(tr);
    });
    
    document.querySelectorAll('.edit-authGroup').forEach(function(btn) {
      btn.onclick = function() {
        var id = parseInt(this.getAttribute('data-id'));
        editAuthGroup(id);
      };
    });
    
    document.querySelectorAll('.delete-authGroup').forEach(function(btn) {
      btn.onclick = function() {
        var id = parseInt(this.getAttribute('data-id'));
        deleteAuthGroup(id);
      };
    });
  }
  
  // 编辑权限分类
  function editAuthGroup(id) {
    var group = authGroupData.find(function(g) {
      return g.id === id;
    });
    
    layer.open({
      type: 1,
      title: '编辑权限分类',
      area: ['520px', '366px'],
      content: document.getElementById('authGroupFormTpl').innerHTML,
      success: function(layero, index) {
        // 使用setTimeout确保DOM完全渲染后再设置表单值
        setTimeout(function() {
          form.val('authGroupForm', {
            id: group.id,
            name: group.name,
            desc: group.desc,
            sort: group.sort || 0
          });
        }, 100);
        
        // 使用独特的filter名称避免事件重复绑定
        var filterName = 'submitAuthGroupEdit_' + index;
        // 修改表单按钮的lay-filter属性
        layero.find('button[lay-submit]').attr('lay-filter', filterName);
        
        form.on('submit(' + filterName + ')', function(data) {
          // 提交修改到后端
          var loading = layer.load(2);
          
          // 准备提交数据
          var submitData = {
            id: parseInt(data.field.id),
            name: data.field.name,
            desc: data.field.desc,
            sort: parseInt(data.field.sort) || 0
          };
          
          // 发送PUT请求更新分类
          fetch('/auth/group', {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(submitData)
          })
          .then(response => {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
              return response.json();
            } else {
              throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
            }
          })
          .then(result => {
            layer.close(loading);
            if (result.result) {
              // 更新本地数据
              group.name = data.field.name;
              group.desc = data.field.desc;
              group.sort = parseInt(data.field.sort) || 0;
              group.updateTime = formatTime(new Date());
              
              // 重新获取数据以保证排序
              fetchData();
              layer.close(index);
              layer.msg('权限分类已更新');
            } else {
              layer.msg('更新失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
            }
          })
          .catch(error => {
            layer.close(loading);
            layer.msg('请求失败: ' + error.message, {icon: 2});
            console.error('Error:', error);
          });
          
          return false;
        });
      }
    });
  }
  
  // 添加权限分类
  function addAuthGroup() {
    layer.open({
      type: 1,
      title: '添加权限分类',
      area: ['520px', '366px'],
      content: document.getElementById('authGroupFormTpl').innerHTML,
      success: function(layero, index) {
        // 确保表单渲染完成后再设置值
        setTimeout(function() {
          form.val('authGroupForm', {
            id: '',
            name: '',
            desc: '',
            sort: 0
          });
        }, 100);
        
        // 使用独特的filter名称避免事件重复绑定
        var filterName = 'submitAuthGroupAdd_' + index;
        // 修改表单按钮的lay-filter属性
        layero.find('button[lay-submit]').attr('lay-filter', filterName);
        
        form.on('submit(' + filterName + ')', function(data) {
          // 提交新增到后端
          var loading = layer.load(2);
          
          // 准备提交数据，排除id字段
          var submitData = {
            name: data.field.name,
            desc: data.field.desc,
            sort: parseInt(data.field.sort) || 0
          };
          
          // 发送POST请求添加分类
          fetch('/auth/group', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(submitData)
          })
          .then(response => {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
              return response.json();
            } else {
              throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
            }
          })
          .then(result => {
            layer.close(loading);
            if (result.result) {
              // 重新获取数据以保证排序
              fetchData();
              layer.close(index);
              layer.msg('权限分类已添加');
            } else {
              layer.msg('添加失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
            }
          })
          .catch(error => {
            layer.close(loading);
            layer.msg('请求失败: ' + error.message, {icon: 2});
            console.error('Error:', error);
          });
          
          return false;
        });
      }
    });
  }
  
  // 删除权限分类
  function deleteAuthGroup(id) {
    var relatedAuth = authData.filter(function(auth) {
      return auth.groupID === id;
    });
    
    if (relatedAuth.length > 0) {
      layer.alert('无法删除此分类，因为它关联了 ' + relatedAuth.length + ' 个权限组！', { icon: 2 });
      return;
    }
    
    layer.confirm('确定要删除这个分类吗？', {
      icon: 3,
      title: '删除分类'
    }, function(index) {
      // 提交删除到后端
      var loading = layer.load(2);
      
      // 发送DELETE请求删除分类
      fetch('/auth/group?id=' + id, {
        method: 'DELETE'
      })
      .then(response => {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          return response.json();
        } else {
          throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
        }
      })
      .then(result => {
        layer.close(loading);
        if (result.result) {
          authGroupData = authGroupData.filter(function(group) {
            return group.id !== id;
          });
          
          renderAuthGroup();
          layer.close(index);
          layer.msg('分类已删除');
        } else {
          layer.msg('删除失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
        }
      })
      .catch(error => {
        layer.close(loading);
        layer.msg('请求失败: ' + error.message, {icon: 2});
        console.error('Error:', error);
      });
    });
  }
  
  // 事件绑定
  document.getElementById('addAuthGroupBtn').onclick = addAuthGroup;
  document.getElementById('searchAuthGroupBtn').onclick = renderAuthGroup;
  document.getElementById('refreshAuthGroupBtn').onclick = fetchData;
  
  // 初始化
  fetchData();
});
</script>
